﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Reviewer.Entities.Services;
using Reviewer.Data;
using System.Web;
using Reviewer.Entities;
using System.Web.Caching;

namespace Reviewer.Business.Services
{
    internal class MembersAttributeService : BaseService, IMembersAttributeService
    {
        internal MembersAttributeService()
            : base()
        {
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        public MembersAttribute[] GetAttributes(string userName)
        {
            ReviewerDBContext context = new ReviewerDBContext();
            var membership = (from m in context.Members where m.UserName == userName select m).FirstOrDefault();
            if (membership != null)
            {
                return (from m in context.MembersAttribute where m.MembersId == membership.Id select m).ToArray();
            }

            return new MembersAttribute[0];
        }

        public MembersAttribute[] GetAttributes(string userName, string keyName)
        {
            ReviewerDBContext context = new ReviewerDBContext();
            var membership = (from m in context.Members where m.UserName == userName select m).FirstOrDefault();
            if (membership != null)
            {
                return (from m in context.MembersAttribute where m.MembersId == membership.Id && m.Key == keyName select m).ToArray();
            }

            return new MembersAttribute[0];
        }

        public string GetUserNameFromAttribute(string keyName, string value)
        {
            var context = new ReviewerDBContext();
            var attribute = (from m in context.MembersAttribute where m.Key == keyName && m.Value == value select m).FirstOrDefault();
            if (attribute != null)
            {
                var members = (from m in context.Members where m.Id == attribute.MembersId select m).FirstOrDefault();
                if (members != null)
                {
                    return members.UserName;
                }
            }

            return String.Empty;
        }
    }
}
